package com.future.common.listener.nettysocketio;

import java.util.Date;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.future.dao.SocketClientDao;
import com.future.model.SocketClient;
import com.future.service.AuthenticationService;
import com.jfinal.aop.Inject;

import net.minidev.json.JSONObject;

public class ConnectedListener implements ConnectListener {
	@Inject
	private SocketClientDao socketClientDao;
	@Inject
	private AuthenticationService authenticationService;
	/**
	 * 建立连接增加或者更新记录
	 */
	@Override
	public void onConnect(SocketIOClient client) {
		String token = client.getHandshakeData().getSingleUrlParam("Authorization");
		JSONObject result = this.authenticationService.parseToken(token);
		String userid = result.getAsString("userid");
		String sessionId = client.getSessionId().toString();
		SocketClient socketClient = this.socketClientDao.findById(sessionId);
		//新增
		if(socketClient==null){
			socketClient = new SocketClient();
			socketClient.setSessionid(sessionId);
			socketClient.setConnected(1);
			socketClient.setLastconnecteddate(new Date());
			socketClient.setUserid(userid);
			socketClient.save();
		}else{
			socketClient.setConnected(1);
			socketClient.setLastconnecteddate(new Date());
			socketClient.update();
		}
	}

}
